package com.ciwong.epaper.modules.pad.homeworkwidget.presenter;


import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.bean.SchoolDetail;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.me.bean.UserInforDetailBean;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.modules.pad.homeworkwidget.common.util.LruCacheCallBack;
import com.ciwong.epaper.modules.pad.homeworkwidget.widget.remoteviews.HomeworkRemoteViewsDecorator;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;

import java.io.Serializable;
import java.util.List;

public class PersonalInfor implements Runnable {


    private String TAG = "PersonalInfor";
    private static PersonalInfor instance;
    private static Context mContext;
    private UserInfoBase mUserInfoBase;
    private SchoolDetail mSchoolDetail;
    private Clazz mClazz;
    private int level = 1;
    private List<ServiceDetail> mServiceDetails;

    private PersonalInfor() {
    }

    public static PersonalInfor getInstance(Context context) {
        mContext = context;
        if (instance == null)
            instance = new PersonalInfor();
        return instance;
    }

    /**
     * 刷新个人信息
     * 1.appwidget创建时
     * 2.登录成功时
     * 3.亮屏时
     *
     * @param isLogin 登陆成功
     * @param isBindPhone 绑定成功
     */
    private static long oldTime = 0;
    private static long newTime = 0;
    private static long duration = 1 * 1000;

    public void refreshPerInfor(boolean isLogin, boolean isBindPhone) {
        newTime = System.currentTimeMillis();
        if (newTime - oldTime < duration) {//控制请求次数
            return;
        }
        oldTime = newTime;
        if (isLogin && isBindPhone) {//只有两者都成功时才更新数据
            new Thread(this).start();
        }

    }

    private void init() {
        initLocalData();
        refreshViewLocalData();
        initNetDataAndRefreshView();
    }

    private void initLocalData() {
        try {
            mUserInfoBase = EApplication.getInstance().getUserInfoBase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mSchoolDetail = EApplication.getInstance().getSchoolDetail();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mClazz = EApplication.getInstance().getClazz();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mServiceDetails = EApplication.getInstance().getServiceDetails();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 本地数据 刷新view
     */
    private void refreshViewLocalData() {
        if (null != mServiceDetails) {
            setMemberUiInfo(mServiceDetails);
        }
        refreshSchoolView(mSchoolDetail, mClazz);
        if (mUserInfoBase != null) {
            String baseInfor = "Lv." + level + " | " + mUserInfoBase.getRealName() + " | " + mUserInfoBase.getUserId();
            HomeworkRemoteViewsDecorator.getInstance().setPersonalViewBaseIfor(mContext, baseInfor);
        }
        if (mUserInfoBase != null && !TextUtils.isEmpty(mUserInfoBase.getAvatar())) {
            Bitmap bitmap = LruCacheCallBack.bitmapCallMap(mUserInfoBase.getAvatar(), mContext);
            HomeworkRemoteViewsDecorator.getInstance().setPersonalViewHeadBitmap(mContext, bitmap);
        } else {
            HomeworkRemoteViewsDecorator.getInstance().setPersonalViewHeadResource(mContext, R.mipmap.ic_widget_login_head);
        }
    }

    /**
     * 刷新学校和年级信息
     *
     * @param schoolDetail
     * @param clazz
     */
    private void refreshSchoolView(SchoolDetail schoolDetail, Clazz clazz) {

        String schoolInfor = "";
        if (schoolDetail != null) {
            schoolInfor = schoolDetail.getSchoolName();
        }
        if (clazz != null) {
            if (!TextUtils.isEmpty(schoolInfor)) schoolInfor += "，";
//            schoolInfor += GradeSelectDialog.getGradeNameById(mClazz.getGradeId());
            schoolInfor += mClazz.getClassName();
        }
        if (!TextUtils.isEmpty(schoolInfor)) {
            HomeworkRemoteViewsDecorator.getInstance().setPersonalViewSchool(mContext, schoolInfor);
        } else {
            schoolInfor = mContext.getResources().getString(R.string.widget_has_no_join_class);
            if (!HomeworkWidgetCheckState.isJoinClass())
                HomeworkRemoteViewsDecorator.getInstance().setPersonalViewSchool(mContext, schoolInfor);
        }
    }

    private void initNetDataAndRefreshView() {
//        getUserInforRank();//个人基本信息
        getSchoolByServer();//学校信息
        getClszzByServer();//班级信息
//        getMemberInfo();//会员信息
    }

    /**
     * 获取等级个人信息，头像
     */
    private void getUserInforRank() {

        MeDao.getInstance().getUserInforDetail(new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d(TAG, "data:" + data + errorCode);
                Log.d(TAG, "########刷新 个人信息 getUserInforRank failed#########" + data + errorCode);
            }

            @Override
            public void failed(Object data) {
                failed(-121, data);
            }

            @Override
            public void success(Object data) {
                super.success(data);
                Log.d(TAG, "########刷新 个人信息 getUserInforRank success#########");
                if (data == null)
                    return;
                UserInforDetailBean userInforAndPointRankBean = (UserInforDetailBean) data;
                refrashPersonalAndHeadInfor(userInforAndPointRankBean);
                CWLog.d(TAG, "data:" + data);
            }


        });
    }

    /**
     * 修改个人基本信息以及头像信息
     *
     * @param userInforAndPointRankBean
     */
    private void refrashPersonalAndHeadInfor(final UserInforDetailBean userInforAndPointRankBean) {
        if (userInforAndPointRankBean == null) return;
        if (!TextUtils.isEmpty(userInforAndPointRankBean.getAvatar())) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bitmap = LruCacheCallBack.bitmapCallMap(userInforAndPointRankBean.getAvatar(), mContext);
                    HomeworkRemoteViewsDecorator.getInstance().setPersonalViewHeadBitmap(mContext, bitmap);
                }
            });
        } else {
            HomeworkRemoteViewsDecorator.getInstance().setPersonalViewHeadResource(mContext, R.mipmap.ic_widget_login_head);
        }
        if (mUserInfoBase != null) {
            String baseInfor = "Lv." + userInforAndPointRankBean.getLevel() + " | " + userInforAndPointRankBean.getRealName() + " | " + userInforAndPointRankBean.getUserId();
            HomeworkRemoteViewsDecorator.getInstance().setPersonalViewBaseIfor(mContext, baseInfor);
        }
    }

    /**
     * 获取个人会员信息
     */
    public void getMemberInfo() {
        //我的服务镇南关有购买未过期的显示VIP  无购买有试用显示试用 无购买无试用隐藏
        Log.d(TAG, "########刷新VIPgetMemberInfo#########");
        UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
        if (null != userInfoBase) {
            MeDao.getInstance().getServiceDetails(EApplication.getInstance(), EApplication.BRAND_ID, userInfoBase.getUserId(), 0, new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                    Log.d(TAG, "########刷新VIPgetMemberInfo failed#########" + data + errorCode);
                }

                @Override
                public void failed(Object data) {
                    super.failed(data);
                    Log.d(TAG, "########刷新VIPgetMemberInfo failed#########" + data);
                }

                @Override
                public void success(Object data) {
                    Log.d(TAG, "########刷新VIPgetMemberInfo success#########");
                    List<ServiceDetail> list = (List<ServiceDetail>) data;
                    SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST, (Serializable) list);
                    EApplication.getInstance().setServiceDetails(list);
                    setMemberUiInfo(list);
                }
            });
        }
    }

    /**
     * 修改个人会员信息
     *
     * @param serviceDetails
     */
    private void setMemberUiInfo(List<ServiceDetail> serviceDetails) {
        String isVip = "";
        if (serviceDetails != null) {
            for (ServiceDetail s : serviceDetails) {
                if (s.isVip()) {
                    isVip = "VIP";
                    break;
                } else if (!s.isbExpired() && s.getSign() != 3 && !s.isBuy()) {//!s.isbExpired()&&s.getSign()!=3&&!s.isBuy()
                    isVip = "试用";
                }
            }
        }
        HomeworkRemoteViewsDecorator.getInstance().setPersonalViewVip(mContext, isVip);
    }

    /**
     * 获取 修改学校信息
     */
    private void getSchoolByServer() {
        Log.d(TAG, "########刷新学校信息#########");
        if (null == EApplication.getInstance().getUserInfoBase()) {
            return;
        }
        MeDao.getInstance().getSchoolInfo(new BaseExtCallBack(mContext, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(Object data) {
                Log.d(TAG, "########刷新学校信息 #########failed" + data);
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                Log.d(TAG, "########刷新学校信息 #########" + data + errorCode);
            }

            @Override
            public void success(Object data) {
                Log.d(TAG, "########刷新学校信息 success#########");
                List<SchoolDetail> schoolDetails = (List<SchoolDetail>) data;
                if (schoolDetails.isEmpty()) {
                    mSchoolDetail = null;
                } else {
                    mSchoolDetail = schoolDetails.get(0);
                    try {
                        //刷新数据库的schoolId
                        if (EApplication.PLATFORM_ENV == EApplication.PLATFORM_PAD && mSchoolDetail != null) {
                            int schoolId = mSchoolDetail.getSchoolId();
                            LoginToken loginToken = LoginToken.queryTokenAndUserInfo(mContext.getContentResolver());
                            if (null != loginToken) {
                                if (loginToken.getSchoolId() != schoolId) {
                                    loginToken.setSchoolId(schoolId);
                                    LoginToken.updateSchoolId(mContext.getContentResolver(), loginToken);
                                }

                            }
                        }
                        EApplication.getInstance().setMySchool(mSchoolDetail);
                        CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_USER_SCHOOL_BASE, mSchoolDetail);
                        CWSys.setSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_SCHOOL + EApplication.getInstance().getUserInfoBase().getUserId(), mSchoolDetail);
                    } catch (Exception e) {

                    }
                }
                refreshSchoolView(mSchoolDetail, mClazz);
                EApplication.getInstance().setSchoolDetail(mSchoolDetail);
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_SCHOOL, mSchoolDetail);
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_ALL_SCHOOL, (Serializable) schoolDetails);
            }
        });
    }

    /**
     * 获取 修改班级信息
     */
    private void getClszzByServer() {
        SchoolDetail mySchool = EApplication.getInstance().getMySchool();
        if (null == mySchool) {
            return;
        }
        MeDao.getInstance().getClassList(EApplication.BRAND_ID, 2, mySchool.getSchoolId(), new BaseCallBack() {
            @Override
            public void success(Object data) {
                final List<Clazz> clazzs = (List<Clazz>) data;
                if (clazzs == null || clazzs.isEmpty()) {
                    mClazz = null;
                } else {
                    int indexOf = clazzs.indexOf(mClazz);
                    if (indexOf < 0) {
                        indexOf = 0;
                    }
                    mClazz = clazzs.get(indexOf);
                }
                refreshSchoolView(mSchoolDetail, mClazz);
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, mClazz);
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST, (Serializable) clazzs);
                EApplication.getInstance().setClazzs(clazzs);
                EApplication.getInstance().setClazz(mClazz);

            }

            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d(TAG, "拉取班级列表失败:" + errorCode);
                failed(data);
            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "拉取班级列表失败:" + data);
            }
        });
    }

    @Override
    public void run() {
        init();
    }
}
